package com.ytkj.ygAssist.viewControl;

import com.ytkj.ygAssist.main.YunGouLoginServer;
import com.ytkj.ygAssist.main.YunGouServer;
import com.ytkj.ygAssist.server.GetUserBuyServer;
import com.ytkj.ygAssist.server.SelectAssistPublishs;
import com.ytkj.ygAssist.tools.Config;
import com.ytkj.ygAssist.tools.JFrameListeningInterface;
import com.ytkj.ygAssist.tools.MyLog;
import com.ytkj.ygAssist.view.IntelligentMonitoring;
import com.ytkj.ygAssist.view.myView.HintDialog;
import com.ytkj.ygAssist.view.myView.ShowMyMenu;

import org.jfree.data.category.DefaultCategoryDataset;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

public class IntelligentMonitoringControl extends IntelligentMonitoring {
	private static final long serialVersionUID = 1L;

	private int progressBarValue = 0;// 记录显示进度条进度
	public String newestCodeID = null;// 最新期数网址id
	public boolean isAutoBuy = false;// 是否开启挂机自动下注
	public boolean isBuy = true;// 是否已经购买

	public IntelligentMonitoringControl() {
		super();
		addButtonMouseListener();
		setListening();
	}

	/*
	 * 添加按钮监听事件
	 */
	private void addButtonMouseListener() {
		// 添加开始监听按钮事件
		startMonitorButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				if (startMonitorButton.getText().equals("开始监控")) {
					if (Config.isAssistOverdue) {
						ShowMyMenu.ShowAssistOverdue();
						return;
					}
					if (textField.getText().equals("")) {
						label_1.setText("请输入监控内容");
						return;
					}
					label_9.setText("");
					textField.setEnabled(false);
					comboBox.setEnabled(false);
					startMonitorButton.setText("停止监控");
					YunGouServer.setIntelligentMonitoring(true, textField.getText().trim(),
							Integer.toString(comboBox.getSelectedIndex() * 5 + 6), foreknowInterface);
				} else {
					startMonitorButton.setText("正在停止");
					startMonitorButton.setEnabled(false);
					YunGouServer.setIntelligentMonitoring(false, null, null, foreknowInterface);
				}
				IntelligentMonitoringControl.this.repaint();
			}
		});

		// 添加购买按钮事件
		buyButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (startMonitorButton.getText().equals("开始监控")) {
					HintDialog.startExpiringHint("请先开启监控");
					return;
				}
				if (!YunGouLoginServer.getUserServer().getIsLogin()) {
					HintDialog.startExpiringHint(HintDialog.yungouLogin, "您还未登录1元云购账户，请先登录后再使用购买功能，谢谢！！！");
					return;
				}
				buyButton.setEnabled(false);
				if (isBuy) {
					isBuy = false;
					YunGouServer.buyGoods(newestCodeID, spinner.getValue().toString(), foreknowInterface);
				}
			}
		});

		// 添加刷新余额按钮事件
		refreshButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				refreshBalance();
			}
		});

		// 添加删除购物车按钮事件
		deleteCartLabel.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				deleteCart();
			}
		});

		// 添加挂机按钮事件
		guajiButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (guajiButton.getText().equals("挂机")) {
					if ((Integer) autoBuy_spinner_3.getValue() >= (Integer) autoBuy_spinner_4.getValue()) {
						HintDialog.startExpiringHint("请填写正确的挂机范围");
						return;
					}
					if (!YunGouLoginServer.getUserServer().getIsLogin()) {
						HintDialog.startExpiringHint(HintDialog.yungouLogin, "您还未登录1元云购账户，请先登录后再使用购买功能，谢谢！！！");
						return;
					}
					isAutoBuy = true;
					setAutoBuySpinnerEnabled(false);
				} else {
					isAutoBuy = false;
					setAutoBuySpinnerEnabled(true);
				}
			}
		});
	}

	/*
	 * 设置查询回调事件
	 */
	private void setListening() {
		foreknowInterface = new JFrameListeningInterface() {
			@Override
			public void setFrameListeningText(String FrameName, String[] text) {
				if (FrameName.equals("1")) {
					progressBar.setMaximum(Integer.parseInt(text[3]));
					progressBar.setValue(Integer.parseInt(text[2]));
					progressBar_1.setVisible(true);
					label_1.setText("当前第" + text[1] + "云");
					label_16.setText("当前第" + text[1] + "云");
					label_2.setText(text[2]);
					label_4.setText(text[3]);
					label_6.setText(text[4]);
					newestCodeID = text[0];
					setLinedataset(text[1], text[3]);
				} else if (FrameName.equals("2")) {
					try {
						int value = Integer.parseInt(text[2]);
						progressBar.setValue(value);
//						progressBar
//								.setString((int) Math.ceil(value * 100.0f / ((double) progressBar.getMaximum()-2)) + "%");
						label_2.setText(text[2]);
						label_6.setText(text[4]);
						listeningAutoBuy(text[2]);
					} catch (Exception e) {
					}
				} else if (FrameName.equals("3")) {
					if (text[0].equals(textField.getText().trim()) && startMonitorButton.getText().equals("停止监控")) {
						try {
							String period = label_1.getText();
							String datasetStrint = null;
							String label_8Text = null;
							if (!text[5].equals("")) {
								datasetStrint = text[5];
								label_8Text = "第" + text[1] + "云中奖人:" + text[3] + " 买了" + text[4] + "次";
							} else {
								datasetStrint = "0";
								label_8Text = "第" + text[1] + "云  正在计算中，请等待。。。";
							}
							setDataset(text[1], datasetStrint);
							if (Integer.parseInt(text[1]) + 1 == Integer
									.parseInt(period.substring(3, period.indexOf("云")))) {
								label_8.setText(label_8Text);
							}
						} catch (Exception e) {
						}
					}
				}
			}

			@Override
			public void setFrameText(String FrameName, String text) {
				if (FrameName.equals("setGoodsName")) {
					label_9.setText(text);
				} else if (FrameName.equals("setGoodsNameError")) {
					label_8.setText("无法找到该商品或网络异常");
					textField.setEnabled(true);
					comboBox.setEnabled(true);
					startMonitorButton.setText("开始监控");
				} else if (FrameName.equals("goodsoldOut")) {
					label_8.setText("该商品已经下降了");
					textField.setEnabled(true);
					comboBox.setEnabled(true);
					startMonitorButton.setText("开始监控");
				} else if (FrameName.equals("webError")) {
					final String[] testStr = text.split("___");
					MyLog.outLog("查询错误，正在重新开启查询", testStr[0], testStr[1]);
					new Thread(new Runnable() {
						public void run() {
							SelectAssistPublishs.getYungouPublishs(testStr[0], testStr[1], "1");
							GetUserBuyServer.getUserBuyServer(testStr[2]).GetGoodsPeriodInfo(testStr[0], testStr[1],
									testStr[2], true);
						}
					}).start();
				} else if (FrameName.equals("newestCodeID")) {
					newestCodeID = text;
					if (guajiButton.getText().equals("停止")) {
						isAutoBuy = true;
					}
				} else if (FrameName.equals("newestPeriod")) {
					label_1.setText("当前第" + text + "云");
					label_16.setText("当前第" + text + "云");
					try {
						DefaultCategoryDataset linedataset = (DefaultCategoryDataset) plot.getDataset();
						linedataset.removeColumn(0);
						linedataset.addValue(0, // 值
								"", // 哪条数据线
								Integer.toString(Integer.parseInt(text) - 1)); // 对应的横轴
					} catch (Exception e) {
					}
				} else if (FrameName.equals("stopRemind")) {
					label_1.setText("请输入监控内容");
					label_8.setText("最近一期中奖情况");
					label_9.setText("");
					label_16.setText("");
					plot.setDataset(null);// 定义图标对象
					progressBar.setValue(0);
					label_2.setText("0");
					label_4.setText("0");
					label_6.setText("0");
					newestCodeID = "0";
					textField.setEnabled(true);
					comboBox.setEnabled(true);
					startMonitorButton.setEnabled(true);
					progressBar_1.setVisible(false);
					startMonitorButton.setText("开始监控");
					if (isAutoBuy) {
						isAutoBuy = false;
						setAutoBuySpinnerEnabled(true);
					}
				} else if (FrameName.equals("buySucceed")) {
					HintDialog.startExpiringHint(HintDialog.buySucceed, text);
					buyButton.setEnabled(true);
					isBuy = true;
					refreshBalance();// 刷新余额
				} else if (FrameName.equals("buyError")) {
					HintDialog.startExpiringHint("未能购买成功,请检查账户余额，或网络问题");
					buyButton.setEnabled(true);
					isBuy = true;
					refreshBalance();// 刷新余额
				} else if (FrameName.equals("refresProgressBar")) {// 刷新进度条
					progressBarValue = progressBarValue == 100 ? 0 : progressBarValue + 50;
					progressBar_1.setValue(progressBarValue);
				}
			}
		};
	}

	// 监听自动下注
	private void listeningAutoBuy(String startBuyNum) {
		if (isAutoBuy) {
			int startBuyNumInt = Integer.parseInt(startBuyNum);
			if ((Integer) autoBuy_spinner_3.getValue() < startBuyNumInt
					&& (Integer) autoBuy_spinner_4.getValue() > startBuyNumInt) {
				if (isAutoBuy) {
					isAutoBuy = false;
					YunGouServer.buyGoods(newestCodeID, autoBuy_spinner_1.getValue().toString(), foreknowInterface);
					MyLog.outLog("自动购买了", newestCodeID, autoBuy_spinner_1.getValue().toString());
					if (autoBuy_spinner_2.getValue().toString().equals("1")) {
						setAutoBuySpinnerEnabled(true);
					} else {
						autoBuy_spinner_2.setValue((Integer) autoBuy_spinner_2.getValue() - 1);
					}
				}
			}
		}
	}

	// 随机购买
	private void randomBuy() {
		new Thread(new Runnable() {
			public void run() {
				while (true) {
					long time = 1000 / 100;
					boolean isTime = true;
					int i = 0;
					while (isTime && i < 100) {
						MyLog.threadSleep(time);
						i++;
					}
					System.out.println("的");
				}
			}
		}).start();
	}

	// 设置自动购买按钮是否能用
	private void setAutoBuySpinnerEnabled(boolean isTrue) {
		autoBuy_spinner_1.setEnabled(isTrue);
		autoBuy_spinner_2.setEnabled(isTrue);
		autoBuy_spinner_3.setEnabled(isTrue);
		autoBuy_spinner_4.setEnabled(isTrue);
		String guajiButtonString = isTrue ? "挂机" : "停止";
		guajiButton.setText(guajiButtonString);
	}

	// 初始化数据
	private void setLinedataset(String codePeriod, String upperBound) {
		DefaultCategoryDataset linedataset = new DefaultCategoryDataset();
		int queryNum = comboBox.getSelectedIndex() * 5 + 5;
		int codePeriodInt = Integer.parseInt(codePeriod);
		for (int i = Integer.parseInt(codePeriod) - queryNum; i < codePeriodInt; i++) {
			linedataset.addValue(0, // 值
					"", // 哪条数据线
					Integer.toString(i)); // 对应的横轴
		}
		plot.setDataset(linedataset);// 定义图标对象
		int maxInt = Integer.parseInt(upperBound);
		plot.getRangeAxis().setUpperBound(maxInt + maxInt / 20);// 数据轴上的显示最大值
		// plot.getRangeAxis().setUpperBound(maxInt);// 数据轴上的显示最大值

	}

	// 设置数据
	private void setDataset(String codePeriod, String buyPosition) {
		DefaultCategoryDataset linedataset = (DefaultCategoryDataset) plot.getDataset();
		if (linedataset != null) {
			try {
				if (linedataset.getValue("", codePeriod).intValue() >= 0) {
					linedataset.setValue(Integer.parseInt(buyPosition), "", codePeriod);
				}
			} catch (Exception e) {
			}
		}
		plot.setDataset(linedataset);// 定义图标对象
	}

	public void setTextFieldContent(String goodsID) {
		textField.setText(goodsID);
	}

	public ArrayList<String> getNotData() {
		DefaultCategoryDataset linedataset = (DefaultCategoryDataset) plot.getDataset();
		ArrayList<String> values = new ArrayList<String>();
		if (linedataset != null) {
			try {
				for (Object key : linedataset.getColumnKeys()) {
					if (linedataset.getValue("", (String) key).intValue() == 0) {
						values.add((String) key);
					}
				}
			} catch (Exception e) {
			}
		}
		return values;
	}

	/*
	 * 刷新余额
	 */
	public void refreshBalance() {
		if (YunGouLoginServer.getUserServer().getIsLogin()) {
			new Thread(new Runnable() {
				public void run() {
					try {
						String balance = YunGouLoginServer.getUserServer().getUserBalance();
						balanceLabel.setText("余额:" + balance);
						balanceLabel.setVisible(true);
						refreshButton.setVisible(true);
						String cartlabel = YunGouLoginServer.getUserServer().getCartlabel();
						cartLabel.setText("(" + cartlabel + ")");
					} catch (Exception e2) {
					}
				}
			}).start();
		} else {
			balanceLabel.setVisible(false);
			refreshButton.setVisible(false);
			cartLabel.setText("");
		}
	}

	/*
	 * 清除购物车
	 */
	private void deleteCart() {
		if (YunGouLoginServer.getUserServer().getIsLogin()) {
			new Thread(new Runnable() {
				public void run() {
					try {
						YunGouLoginServer.getUserServer().deleteCart();
						String cartlabel = YunGouLoginServer.getUserServer().getCartlabel();
						cartLabel.setText("(" + cartlabel + ")");
					} catch (Exception e2) {
					}
				}
			}).start();
		}
	}

	public JFrameListeningInterface getJFrameListeningInterface() {
		if (startMonitorButton.getText().equals("停止监控")) {
			return foreknowInterface;
		}
		return null;
	}
}
